package com.todo.gateway.conf;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.todo.common.common.entity.CurrentStaff;
import com.todo.common.common.entity.CurrentUser;
import com.todo.gateway.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author azhebuxing
 * @date 2025/2/21 18:22
 * @description
 */
@Slf4j
@Component
public class InjectBodyInfoFilter implements WebFilter, Ordered {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();

        // 从请求头中获取 Token
        String token = headers.getFirst(HttpHeaders.AUTHORIZATION);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        } else {
            return chain.filter(exchange); // 如果没有 Token，直接放行
        }

        Boolean todoUser = jwtUtils.isTodoUser(token);
        if (todoUser) {
            return todoUserFilter(exchange, chain, request, token);
        } else {
            return staffFilter(exchange, chain, request, token);
        }
    }

    private Mono<Void> staffFilter(ServerWebExchange exchange, WebFilterChain chain, ServerHttpRequest request, String token) {
        // 解析 Token 获取用户信息
        CurrentStaff staff = jwtUtils.getCurrentStaff(token);
        if (staff == null) {
            return chain.filter(exchange); // 如果 Token 无效，直接放行
        }

        // 修改请求体，注入用户信息
        if (HttpMethod.POST.equals(request.getMethod()) || HttpMethod.PUT.equals(request.getMethod())
                || HttpMethod.PATCH.equals(request.getMethod()) || HttpMethod.DELETE.equals(request.getMethod())) {
            return DataBufferUtils.join(request.getBody())
                    .flatMap(dataBuffer -> {
                        if (dataBuffer.readableByteCount() == 0) {
                            // 请求体为空，直接放行
                            return chain.filter(exchange);
                        }

                        byte[] bytes = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(bytes);
                        DataBufferUtils.release(dataBuffer);

                        String body = new String(bytes, StandardCharsets.UTF_8);
                        String modifiedBody = injectStaffIntoBody(body, staff);

                        return modifyRequestBody(exchange, chain, modifiedBody);
                    });
        }

        return chain.filter(exchange);
    }

    private Mono<Void> todoUserFilter(ServerWebExchange exchange, WebFilterChain chain, ServerHttpRequest request, String token) {
        // 解析 Token 获取用户信息
        CurrentUser currentUser = jwtUtils.getCurrentUser(token);
        if (currentUser == null) {
            return chain.filter(exchange); // 如果 Token 无效，直接放行
        }

        // 修改请求体，注入用户信息
        if (HttpMethod.POST.equals(request.getMethod()) || HttpMethod.PUT.equals(request.getMethod())
                || HttpMethod.PATCH.equals(request.getMethod()) || HttpMethod.DELETE.equals(request.getMethod())) {
            return DataBufferUtils.join(request.getBody())
                    .flatMap(dataBuffer -> {
                        if (dataBuffer.readableByteCount() == 0) {
                            // 请求体为空，直接放行
                            return chain.filter(exchange);
                        }

                        byte[] bytes = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(bytes);
                        DataBufferUtils.release(dataBuffer);

                        String body = new String(bytes, StandardCharsets.UTF_8);
                        String modifiedBody = injectUserIntoBody(body, currentUser);

                        return modifyRequestBody(exchange, chain, modifiedBody);
                    });
        }

        return chain.filter(exchange);
    }

    private Mono<Void> modifyRequestBody(ServerWebExchange exchange, WebFilterChain chain, String modifiedBody) {
        // 由于post的body只能订阅一次，由于上面代码中已经订阅过一次body。所以要再次封装请求到request才行，不然会报错请求已经订阅过
        ServerHttpRequest modifiedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
            @Override
            public Flux<DataBuffer> getBody() {
                // 将修改后的请求体转换为 DataBuffer
                byte[] bytes = modifiedBody.getBytes(StandardCharsets.UTF_8);
                return Flux.just(exchange.getResponse().bufferFactory().wrap(bytes));
            }

            @Override
            public HttpHeaders getHeaders() {
                // 更新 Content-Length 头
                HttpHeaders headers = new HttpHeaders();
                headers.putAll(exchange.getRequest().getHeaders());
                headers.setContentLength(modifiedBody.getBytes(StandardCharsets.UTF_8).length);
                return headers;
            }
        };
        return chain.filter(exchange.mutate().request(modifiedRequest).build());
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE; // 高优先级
    }

    private String injectUserIntoBody(String body, CurrentUser currentUser) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(body);
            ((ObjectNode) rootNode).set("_user", objectMapper.valueToTree(currentUser));
            String modifiedBody = objectMapper.writeValueAsString(rootNode);
            return modifiedBody;
        } catch (Exception e) {
            log.error("Failed to inject user into request body", e);
            return body;
        }
    }

    private String injectStaffIntoBody(String body, CurrentStaff staff) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(body);
            ((ObjectNode) rootNode).set("_staff", objectMapper.valueToTree(staff));
            String modifiedBody = objectMapper.writeValueAsString(rootNode);
            return modifiedBody;
        } catch (Exception e) {
            log.error("Failed to inject staff into request body", e);
            return body;
        }
    }

}
